<template>
  <el-dialog title="分配角色" :model-value="modelValue" width="400px" @close="handleClose">
    <el-select multiple v-model="selectedIds">
      <el-option v-for="role in roleList" :key="role.id" :value="role.id" :label="role.name"></el-option>
    </el-select>
    <template #footer>
      <el-button>取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang='ts'>
import { getAllRoleListApi, getUserRoleIdsByAdminIdApi, allocUserRoleApi } from '@/api'
import { ElMessageBox } from 'element-plus';
import { ref, watch } from 'vue';

const props = defineProps({
  modelValue: { type: Boolean },
  allocId: { type: Number }
})

const emits = defineEmits(['update:modelValue'])

const roleList = ref<IRoleModel[]>([])

// 应该在 弹出的时候 获取 角色列表
watch(() => props.modelValue, () => {
  if (!props.modelValue) return;
  // Promise.all - 传入多个promise实例，当所有实例都完成时，返回一个Promise对象。执行.then 
  Promise.all([getAllRoleListApi(), getUserRoleIdsByAdminIdApi(props.allocId as number)]).then(res => {
    if (res[0].code == 200) {
      roleList.value = res[0].data;
    }
    if (res[1].code === 200) {
      selectedIds.value = res[1].data.map(item => item.id);
    }
  })
})

const handleClose = () => {
  emits('update:modelValue', false)
}

const selectedIds = ref<number[]>([])

const handleConfirm = () => {
  ElMessageBox.confirm('确定分配角色吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    allocUserRoleApi({
      adminId: props.allocId as number,
      roleIds: selectedIds.value
    }).then(res => {

    })
  })

}

</script>
<style lang="less" scoped></style>